
package org.gongliang.common.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.gongliang.jfinal.model.Resources;
import org.gongliang.jfinal.model.Role;
import org.gongliang.jfinal.model.User;

/**
 * 简单的设计，只验证名称和密码，验证码在jfinalValidate中验证
 * @author gxs
 *
 */
public class ShiroDbRealm extends AuthorizingRealm {

	
	
	
	 public String getName() {
	        return "shiroDbRealm";
	    }
	
	 /**
   * 认证回调函数,登录时调用.
   * AuthenticationInfo：验证用户是不是拥有相应的身份
   * 传入用户名密码判断是否有这个人
   */
	@Override
	public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token1) throws AuthenticationException {

		UsernamePasswordToken token = (UsernamePasswordToken) token1;
		
		String username = (String) token.getPrincipal();
		String password = new String((char[])token.getCredentials());
		
		User user = User.dao.login(username, password);
		if(user==null) {
			throw new AuthenticationException("用户名或者密码错误");
		}else if(user.getLocked()) {
			throw new AuthenticationException("用户名已被锁定");
		}
		
		return new SimpleAuthenticationInfo(user, password, getName());
	}
	
	
	/**
	   * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	   * AuthorizationInfo：授权，即权限验证，验证某个已认证的用户是否拥有某个权限；即判断用户是否能做事情，常见的如：验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限；
	   * 传入用户名，判断用户的权限
	   */
		@Override
		public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
			User user = (User) principals.fromRealm(getName()).iterator().next();
			
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if( null == user){
        	return info;
        }
			List<String>  roleIds = user.getRolesIdByUserId(user.getId());
			info.addRoles(roleIds);
			 for(String roleId : roleIds){
	                addResourceOfRole(roleId,info);
	            }
			return info;
		}
		
	    private void addResourceOfRole(String roleId, SimpleAuthorizationInfo info){
	    	List<String> resourceIds = Role.dao.getUserResourcesIds(roleId);
	    	for (int i = 0; i < resourceIds.size(); i++) {
	    		String resourceId =  resourceIds.get(i);
	    		 info.addStringPermission(Resources.dao.findById(resourceId).getPermCode());
			}
	    }
    
    


    /**
     * 更新用户授权信息缓存.
     */
    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }

    /**
     * 清除所有用户授权信息缓存.
     */
    public void clearAllCachedAuthorizationInfo() {
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
        if (cache != null) {
            for (Object key : cache.keys()) {
                cache.remove(key);
            }
        }
    }
}
